package org.wishwork.api.purchase.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.purchase.query.response.PurchaseQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 采购单查询
 * @author: WangYX
 * @create: 2022-04-08 11:31
 * @Version: 1.0.0
 **/

public class PurchaseQueryApi extends Api<List<PurchaseQueryResponse>, PurchaseQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(PurchaseQueryApi.class);

    private Context context;

    public PurchaseQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(PurchaseQueryRequest purchaseQueryRequest) throws Exception {
        String url = "/open/purchase/query";
        Map<String, Object> params = new HashMap<>();
        if (purchaseQueryRequest.getPoIds() != null && purchaseQueryRequest.getPoIds().size() > 0) {
            params.put("po_ids", purchaseQueryRequest.getPoIds());
        }
        if (purchaseQueryRequest.getSoIds() != null && purchaseQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", purchaseQueryRequest.getSoIds());
        }
        return HttpHelper.sendRequest(purchaseQueryRequest, params, url);
    }

    @Override
    protected List<PurchaseQueryResponse> process(JSONObject data, PurchaseQueryRequest purchaseQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<PurchaseQueryResponse> purchaseQueryResponses = datas.toJavaList(PurchaseQueryResponse.class);

        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = purchaseQueryRequest.getPageIndex();
            PurchaseQueryRequest build = purchaseQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<PurchaseQueryResponse> business = business(build);
            purchaseQueryResponses.addAll(business);
        }
        return purchaseQueryResponses;
    }
}
